﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Xml.Linq;
using SES.CMS.DO;
using SES.CMS.BL;

namespace SES.CMS
{
    public partial class ThanhToan : BasePage
    {
        Sendmail sendmail;
        ClientLoginDO obj = new ClientLoginDO();
        ShopingCart vpp = new ShopingCart();
        private static DataTable tb = new DataTable();
        private DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = new sysConfigBL().Select(new sysConfigDO { ConfigID = 1 }).ConfigValue.ToString();

            dt = new DataTable();
                loadGioHang();
            loadTT();
            LoadThongTinThanhToan();
        }

        public void loadTT()
        {

            HttpSessionState ss = HttpContext.Current.Session;
            string session = ss.SessionID;

            if (Session["IDDN"] != null)
            {
                ClientLoginDO obj = new ClientLoginBL().Select(new ClientLoginDO { ClientLoginID = int.Parse(Session["IDDN"].ToString()) });
                txtDC.Text = obj.Address;
                txtEmail.Text = obj.Email;
                txtHT.Text = obj.ClientName;
                txtsdt.Text = obj.Mobile;
            }
        }

        protected void loadGioHang()
        {
          Page.Title = new sysConfigBL().Select(new sysConfigDO { ConfigID = 1 }).ConfigValue.ToString();

            if (Session["GioHang"] != null)
            {
                tb = (DataTable)Session["GioHang"];
                if (dt.Rows.Count == 0)
                {
                    dt.Columns.Add("STT");
                    dt.Columns.Add("SanPhamID");
                    dt.Columns.Add("TenSanPham");
                    dt.Columns.Add("HinhAnh");
                    dt.Columns.Add("SoLuong");
                    dt.Columns.Add("DonGia");
                    dt.Columns.Add("GiamGia");
                    dt.Columns.Add("ThanhTien");
                    dt.Columns.Add("Price");
                    dt.Columns.Add("TotalMoney");
                    dt.Columns.Add("ProductName");
                }
                int i = 0;
                foreach (DataRow dr in tb.Rows)
                {
                    cmsSanPhamDO obj = new cmsSanPhamBL().Select(new cmsSanPhamDO { SanPhamID = Int64.Parse(dr[1].ToString()) });
                    i++;
                    DataRow row = dt.NewRow();
                    row[0] = dr[0];
                    row[1] = dr[1];
                    row[2] = obj.TenSanPham;
                    row[3] = obj.HinhAnh;
                    row[4] = dr[2];
                    row[5] = string.Format("{0:0,0} VNÐ", obj.DonGia);
                    row[6] = obj.GiamGia;
                    row[7] = dr[3];
                    row[8] = string.Format("{0:0,0} USD", obj.Price);
                    row[9] = dr[4];
                    row[10] = obj.ProductName;
                    dt.Rows.Add(row);
                }

                if (dt.Rows.Count > 0)
                {
                    
                    GridGioHang.DataSource = dt;
                    GridGioHang.DataBind();
                    float sum = 0;
                    float totalMoney = 0;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        Label lb = GridGioHang.Rows[j].FindControl("lbThanhTien") as Label;
                        if (Session["lang"].ToString() == "VN")
                        {
                            int s = int.Parse(dt.Rows[j].ItemArray[7].ToString());
                            lb.Text = s.ToString("##,## VNĐ");
                        }
                        else
                        {
                            int s = int.Parse(dt.Rows[j].ItemArray[7].ToString());
                            lb.Text = s.ToString("##,## USD");
                        }
                        sum += float.Parse(dt.Rows[j].ItemArray[7].ToString());
                        totalMoney += float.Parse(dt.Rows[j].ItemArray[9].ToString());
                    }
                    if (Session["lang"].ToString() == "VN")
                    {
                        lblSum.Text = "Tổng: <span style='color:red;font-weight:bold;'>" + sum.ToString("##,## VNÐ") + "</span>";
                        lbThanhTien.Text = "Tổng: <span style='color:green;font-weight:bold;'>" + NumberToStringVN.DocTienBangChu((decimal)sum, " đồng") + "</span";
                    }
                    else
                    {
                        lblSum.Text = "Total money:<span style='color:red;font-weight:bold;'>" + totalMoney.ToString("##,## USD") + "</span>";
                    }
                }
            }
            else
            {
                //if (Session["lang"].ToString() == "VN")
                //{ lbl.Text = "Chua có sản phẩm nào trong giỏ hàng"; }
                //else
                //{
                //    lbl.Text = "No product in cart";
                //}

                lblSum.Text = "";
            }
        }

        public void LoadThongTinThanhToan()
        {
            lblThongTinThanhToan.Text = new sysConfigBL().Select(new sysConfigDO { ConfigID = 13 }).ConfigValue;
        }

        public cmsGioHangDO init()
        {
            HttpSessionState ss = HttpContext.Current.Session;
            string session = ss.SessionID;


            cmsGioHangDO objGioHang = new cmsGioHangDO();
            if (Session["IDDN"] != null)
            {
                obj = new ClientLoginBL().Select(new ClientLoginDO { ClientLoginID = int.Parse(Session["IDDN"].ToString()) });
            }
            else
            {
                obj.ClientLoginID = 0;
                obj.ClientName = txtHT.Text;
                obj.Email = txtEmail.Text;
                obj.Mobile = txtsdt.Text;
                obj.Address = txtDC.Text;
            }
            objGioHang.ClientLoginID = obj.ClientLoginID;
            objGioHang.HinhThucThanhToan = ddlHTTT.SelectedValue;
            if (txtNgayGiaoHang.Text == "")
            {
                objGioHang.NgayDatHang = DateTime.Now;
            }
            else
            {
                objGioHang.NgayDatHang = Convert.ToDateTime(txtNgayGiaoHang.Text);
            }
            objGioHang.SessionID = session;
            objGioHang.XuLy = false;

            return objGioHang;
        }

        protected void btn_Click(object sender, EventArgs e)
        {
            cmsGioHangDO objGioHang = init();
            bool kt = false;
            int kq = 0;
            float sum = 0;
            float totalMoney = 0;
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    objGioHang.SanPhamID = Int64.Parse(dr[1].ToString());
                    objGioHang.SoLuong = Int32.Parse(dr[4].ToString());
                    objGioHang.NgayDatHang = DateTime.Now;
                    if (txtNgayGiaoHang.Text != "")
                    {
                        objGioHang.NgayGiaoHang = Convert.ToDateTime(txtNgayGiaoHang.Text);
                    }
                    objGioHang.XuLy = false;
                    objGioHang.ThanhTien = float.Parse(dr[7].ToString());
                    objGioHang.TotalMoney = float.Parse(dr[9].ToString());
                    objGioHang.HinhThucThanhToan = ddlHTTT.SelectedValue;
                    sum += float.Parse(dr[7].ToString());
                    totalMoney += float.Parse(dr[9].ToString());

                    kq = new cmsGioHangBL().Insert(objGioHang);
                }
                catch
                {
                    kt = true;
                }
            }
            if (kt == false)
            {
                cmsDonHangDO objDonHang = new cmsDonHangDO();
                objDonHang.DiaChiGiaoHang = txtDCGH.Text;
                objDonHang.DiaChi = obj.Address;
                objDonHang.Email = obj.Email;
                objDonHang.GhiChu = txtGC.Text;
                objDonHang.GioHangID = kq;
                objDonHang.HoTen = obj.ClientName;
                objDonHang.HTTT = ddlHTTT.SelectedValue;
                objDonHang.SDT = obj.Mobile;
                objDonHang.SessionID = objGioHang.SessionID;
                objDonHang.TongTien = sum;
                objDonHang.UserID = obj.ClientLoginID;
                objDonHang.TotalMoney = totalMoney;
                objGioHang.XuLy = true;

                kq = new cmsDonHangBL().Insert(objDonHang);
                objDonHang.XuLy = true;

                new cmsGioHangBL().Update(objGioHang);
                Session["GioHang"] = null;

                int kqSendmail = SendMail(objDonHang.HoTen, objDonHang.Email);
                if (kqSendmail == 1)
                    Ultility.Alert("Thông tin đơn hàng đã được gửi tới cho ban quản trị!!!", "/Default.aspx");
                Ultility.Alert("Thông tin đơn hàng đã được gửi tới cho ban quản trị!!!", "/Default.aspx");
            }

        }
        protected string NoiDungMail(string HoTen, string Email)
        {
            string NoiDung = "";
            NoiDung = "Có đơn đặt hàng từ:<b> " + HoTen + "</b><br /> Email: " + Email;
            NoiDung += "<br/> Ngày đặt hàng:" + DateTime.Now.ToShortDateString();
            return NoiDung;
        }
        protected int SendMail(string HoTen, string Email)
        {
            sendmail = new Sendmail();
            sendmail.SmtpMailFrom = "trangtrinoingoaithatcustomer@gmail.com";
            sendmail.SmtpPassword = "noingoaithat";
            sendmail.SmtpPort = 587;
            sendmail.SmtpServer = "smtp.gmail.com";
            sendmail.SmtpUser = "trangtrinoingoaithatcustomer@gmail.com";
            return sendmail.SendMail(new sysConfigBL().Select(new sysConfigDO { ConfigID = 4 }).ConfigValue, "Thông báo đơn đặt hàng từ hệ thống!", NoiDungMail(HoTen, Email), true);
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            Response.Redirect("/GioHang.aspx");
        }

        /* Giỏ hàng*/


        protected void GridGioHang_RowCommand(object sender, GridViewCommandEventArgs e)
        {
        }

        protected void GridGioHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

        }

        protected void GridGioHang_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //Page.Title = new sysConfigBL().Select(new sysConfigDO { ConfigID = 1 }).ConfigValue.ToString();
            //{
            //    if (e.Row.RowType == DataControlRowType.DataRow)
            //    {
            //        Page.Title = new sysConfigBL().Select(new sysConfigDO { ConfigID = 1 }).ConfigValue.ToString();
            //        decimal sum = 0;
            //        decimal dg = 0;
            //        decimal totalmoney = 0;
            //        TextBox lbSL = (TextBox)e.Row.FindControl("txtSL");
            //        Label DG = (Label)e.Row.FindControl("lbDG");
            //        Label GG = (Label)e.Row.FindControl("lbDGG");
            //        Label TT = (Label)e.Row.FindControl("lbThanhTien");
            //        int sl = int.Parse(lbSL.Text);
            //        int gg = int.Parse(GG.Text.Replace("%", "").Trim());
            //        if (Session["lang"].ToString() == "VN")
            //        {
            //            string tem = DG.Text.Replace("VNÐ", "").Trim();
            //            tem = tem.Replace(".", "");
            //            dg = Decimal.Parse(tem);
            //            TT.Text = (sl * (dg - ((dg * gg) / 100))).ToString("##,## VNÐ");
            //        }
            //        if (Session["lang"].ToString() == "EN")
            //        {
            //            string tem = DG.Text.Replace("USD", "").Trim();
            //            tem = tem.Replace(".", "");
            //            dg = Decimal.Parse(tem);
            //            TT.Text = (sl * (dg - ((dg * gg) / 100))).ToString("##,## USD");
            //        }


            //        for (int i = 0; i < GridGioHang.Rows.Count; i++)
            //        {
            //            Label TT1 = (Label)GridGioHang.Rows[i].FindControl("lbThanhTien");
            //            if (Session["lang"].ToString() == "VN")
            //            {
            //                sum += Decimal.Parse(TT1.Text.Replace(" VNÐ", "").Replace(".", "").Trim());
            //            }
            //            if (Session["lang"].ToString() == "EN")
            //            {
            //                totalmoney += Decimal.Parse(TT1.Text.Replace(" USD", "").Replace(".", "").Trim());
            //            }
            //        }
            //        if (Session["lang"].ToString() == "VN")
            //        {
            //            DG.Text = dg.ToString("##,## VNÐ");
            //            lblSum.Text = "Tổng: <span style='color:red;font-weight:bold;'>" + sum.ToString("##,## VNÐ") + "</span>";
            //            lbThanhTien.Text = "Tổng: <span style='color:green;font-weight:bold;'>" + NumberToStringVN.DocTienBangChu((decimal)sum, " đồng") + "</span";
            //        }
            //        if (Session["lang"].ToString() == "EN")
            //        {
            //            lblSum.Text = "Total money: <span style='color:red;font-weight:bold;'>" + totalmoney.ToString("##,## USD") + "</span>";
            //        }
            //    }

            //    if (e.Row.RowType == DataControlRowType.Footer)
            //    {
            //    }
            //    if (e.Row.RowType == DataControlRowType.DataRow)
            //    {
            //        e.Row.Attributes.Add("style", "background-color: #FFFFFF; color: black;");
            //        e.Row.Attributes.Add("onmouseover", "style.backgroundColor='#DEE0BF'");
            //        e.Row.Attributes.Add("onmouseout", "style.backgroundColor='#FFFFFF'");
            //    }
           // }
            //catch { }
    }
        protected void btnCapNhat_Click(object sender, EventArgs e)
        {

        }

        protected void GridGioHang_DataBinding(object sender, System.EventArgs e)
        {
        }

        protected void GridGioHang_DataBound(object sender, EventArgs e)
        {

        }

    }
}
